package com.hgxd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hgxd.entity.pojo.SysRoleMenu;
import com.hgxd.entity.pojo.SysUserRole;
import com.hgxd.entity.vo.ReqRoleMenuVo;
import com.hgxd.exception.ServiceException;
import com.hgxd.mapper.RoleMenuMapper;
import com.hgxd.result.ResultCodeEnum;
import com.hgxd.service.IRoleMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 角色与菜单对应关系 服务实现类
 * </p>
 *
 * @author fsd
 * @since 2023-10-19
 */
@Service("roleMenuServiceImpl")
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, SysRoleMenu> implements IRoleMenuService {

    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateMenuByRoleId(ReqRoleMenuVo reqRoleMenuVo) {
        // 1 删除已有的menuId
        roleMenuMapper.delete(new QueryWrapper<SysRoleMenu>().eq("role_id", reqRoleMenuVo.getRoleId()));
        // 2 添加现有的menuIds
        List<Long> menuIds = reqRoleMenuVo.getMenuIds();
        for (Long menuId : menuIds) {
            Boolean b = roleMenuMapper.insertByRoleId(reqRoleMenuVo.getRoleId(), menuId);
            if (!b) {
                throw new ServiceException(ResultCodeEnum.SERVICE_ERROR, "添加失败");
            }
        }
        return true;
    }
}
